import {
    SetDownloaderLib
} from "./SetDownloaderLib";
import {
    GeneratorFactory
} from "../executor/GeneratorFactory";
import {
    GeneratorExecutor
} from "../executor/GeneratorExecutor";
import moment, { fn } from 'moment'
import {
    SqlLib
} from "../sqlite/SqlLib";
import {
    SqlLibUser
} from "../sqlite/service/SqlLibUser";
import {
    Downloader
} from "../sqlite/model/Downloader";
import {
    Downloaded
} from "../sqlite/model/Downloaded";
import {
    UserResource
} from "../sqlite/model/UserResource";
import {
    SqlLibBook
} from "../sqlite/service/SqlLibBook";
import {
    UUIDUtil
} from "../../utils/UUIDUtil";
import {
    ThumbDownloader
} from "./ThumbDownloader";
import {
    Lesson
} from "../sqlite/model/Lesson";

import vm from '../../../src/renderer/content/main'
import loading from "../../../src/renderer/content/global/loading";

export class DownloadCenter {

    constructor() {
        this.setDownloaders = []; //下载器对象,增加几个状态值：0-初始化成功；1-初始化失败；2-正在下载中；3-已经暂停；4-下载失败(centerStatus)；5-未初始化（针对全书下载）；6-等待下载中
        // this.currentDownloadIndex = [];//当前正在下载的索引
        this.downloaded = []; //已经下载完成的数据 对象数组，对象例子：{lessonId: "", lessonName: "", endTime: "", status: ""}
        this.downloadingSize = 1; //允许同时下载的个数
        // this.initErrorIndex = [];//初始化错误的索引数组
        //视图层 正在下载中的图表
        this.downloadingTable = [];
        this.request = null;
        this.constVar = null;
        this.vueInstance = null;
        this.initCenterMap = new Map();
        this.generator = null //保存状态机，用于暂停后进行下一步操作，
        this.waitDownloadList = []
        this.needLoadingList = []
        this.loadingLessonList = []
        this.immediateRecordList = []
        this.pauseAll = false
        this.startOneLoadTask = this.startOneLoadTask.bind(this)
        this.startNextLoadTask = this.startNextLoadTask.bind(this)
        this.changeViewTables = this.changeViewTables.bind(this)
        this.checkDownloadAndNext = this.checkDownloadAndNext.bind(this)
        this.changeTableState = this.changeTableState.bind(this)
        this.changeCompleteTableState = this.changeCompleteTableState.bind(this)
        this.syncPushDownloadCenter = this.syncPushDownloadCenter.bind(this)
        this.cancelDownLoad = this.cancelDownLoad.bind(this)
        this.pauseDownloadCenter = this.pauseDownloadCenter.bind(this)

        let completeDown = new Downloaded();
        let curDownloaded = [];
        let sqlLib = SqlLib.getInstance(window.$DBDIR);
        let user = SqlLibUser.queryCurrentUser(sqlLib);
        completeDown.userId = user.id;
        let result = sqlLib.selectAllObjectByKeys(completeDown, ["userId"]);
        result.forEach(complete => {
            if (complete.downloadedJson) {
                curDownloaded.push(JSON.parse(complete.downloadedJson));
            }
        });
        vm.$store.commit('addCompletedBook', curDownloaded)
    }

    //单例调用，全局只有这一个实例
    static getInstance (vueInstance) {
        if (!this.instance) {
            //初始化下载器数组 & 已经下载过的数组
            let completeDown = new Downloaded();
            let sqlLib = SqlLib.getInstance(window.$DBDIR);
            let user = SqlLibUser.queryCurrentUser(sqlLib);
            completeDown.userId = user.id;
            let result = sqlLib.selectAllObjectByKeys(completeDown, ["userId"]);
            let curDownloaded = [];
            result.forEach(complete => {
                if (complete.downloadedJson) {
                    curDownloaded.push(JSON.parse(complete.downloadedJson));
                }
            });
            let unCompletes = SqlLibBook.queryUnDownloadLesson(sqlLib);
            let downloadParams = [];
            unCompletes.forEach(unComplete => {
                if (unComplete.downloadParam) {
                    downloadParams.push(JSON.parse(unComplete.downloadParam));
                }
            });
            this.instance = new DownloadCenter();
            if (vueInstance) {
                this.instance.vueInstance = vueInstance;
            }
            this.instance.downloaded = curDownloaded;
            // if(downloadParams.length > 0){
            //     if(user.vipType === "0"){//只有SVIP才给恢复下载功能
            //         _this.instance.syncPushDownloadCenter(downloadParams, function () {
            //             console.log("下载中心列表已经恢复！");
            //         });
            //         _this.instance.initDownloadingTable();
            //     }
            // }
        }
        return this.instance;
    }

    static removeInstance () {
        if (this.instance) {
            this.instance = null;
        }
    }
    

    /**
     * 同步塞入下载中心，不需要初始化
     * @param downloadParams
     * @param isPush 单课时下载时需要动画结束后才能推入vuex
     * @param callback 如果用户塞入callback参数，则不进行后续的下载操作，让用户选择性触发
     */
    // syncPushDownloadCenterNoInit(downloadParams, callback) {
    syncPushDownloadCenter (downloadParams, isPush = true, callback) {
        // console.log(downloadParams);
        console.log("syncPushDownloadCenter:: pre setDownloaders", this.setDownloaders);
        let paramArry = []
        if (downloadParams.length > 0) {
            downloadParams.forEach(param => {
                if (!this.lessonIsDownloading(param.SetDownloadId) ) { //check当前课时是否正在下载  delete   && this.isDownloaderAlowed(param)
                    let obj = {
                        downloaderId: param.SetDownloadId,
                        downloaderInfo: param.DownloaderInfo,
                        centerStatus: 6, //等待中
                        actionStatus: param.ActionStatus,
                        param: param
                    }
                    this.setDownloaders.push(obj);
                    paramArry.push(obj);
                }
            })
            if (!isPush) {
                DownloadCenter.getInstance().initDownloadCenter(paramArry)
                return () => {
                    this.changeTableState(paramArry, 'add')
                }
            } else {
                this.changeTableState(paramArry, 'add')
                DownloadCenter.getInstance().initDownloadCenter(paramArry)
            }
        }
    }

    // initDownloadCenterAndInitTask() {
    initDownloadCenter (paramArry) {
        // let currentIndex = DownloadCenter.getInstance().findDownloadingIndex();
        // let startNum = this.downloadingSize - currentIndex.length;
        // if (startNum <= 0) {
        // if (this.setDownloaders.length === 0) {
        //     this.startDownloadIsInit()
        //     return
        // }
        paramArry.forEach(item => {
            let param = item.param
            if (param.DownloadParams) { //代表是单个课时的下载
                this.initGeneratorListOneLesson(item)
            } else { //代表是全书的下载，刚开始没拿到下载数据
                // return
                this.initGeneratorListAllBook(item)
            }
        })
        // this.runGenerator()
    }

    startDownloadIsInit (targetDown = [], callback) {
        let _this = this
        // let requireDownloader = targetDown.length === 0 ? DownloadCenter.getInstance().findNextDownloadDownloader(startNum) : targetDown
        targetDown.forEach(tempDownloader => {
            //赋值下载中
            tempDownloader.centerStatus = 2;
            _this.changeTableState(tempDownloader, "change");
            tempDownloader.startDownload(function (successCallbackVal) {
                let downloadInfo = tempDownloader.downloaderInfo;
                let action = tempDownloader.actionStatus
                if (action) {
                    if (action === "0") {
                        action = "下载完成"
                    } else if (action === "1") {
                        action = "更新完成"
                    } else if (action === "2") {
                        action = "同步完成"
                    }
                } else {
                    action = "下载完成"
                }
                let downloadedJson = {
                    lessonId: tempDownloader.downloaderId,
                    lessonName: (downloadInfo && downloadInfo.lessonName) ? downloadInfo.lessonName : '',
                    bookName: (downloadInfo && downloadInfo.bookName) ? downloadInfo.bookName : '',
                    publisherName: (downloadInfo && downloadInfo.publisherName) ? downloadInfo.publisherName : '',
                    endTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                    status: action
                }
                try {
                    //更新待下载列表
                    let downloader = new Downloader();
                    downloader.id = tempDownloader.downloaderId;
                    downloader.downloaderStatus = "2";
                    SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);

                    let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
                    //改变下载完成的课时状态
                    if (tempDownloader.errorDownloadTaskIndexes.length > 0) {
                        downloadedJson.status = "部分成功"
                    }
                    //更新已完成列表
                    let complete = new Downloaded();
                    complete.downloadedJson = JSON.stringify(downloadedJson);
                    complete.completeTime = moment().format('YYYY-MM-DD HH:mm:ss');
                    complete.id = tempDownloader.downloaderId + "-" + user.id;
                    complete.reverse1 = tempDownloader.actionStatus;
                    complete.userId = user.id;
                    SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(complete);

                    //更新用户资源关联列表
                    DownloadCenter.getInstance().saveOneLessonRes(tempDownloader).then(() => {
                        // 触发一个改变单课时下载遮罩层的事件
                        console.log("发送changeDownloadStatus 事件")
                        let changeEvent = new CustomEvent('changeDownloadStatus', {
                            detail: {
                                lessonId: tempDownloader.downloaderId,
                                actionStatus: tempDownloader.actionStatus
                            }
                        });
                        window.dispatchEvent(changeEvent);
                    });
                } catch (e) {
                    console.log(e);
                }
                DownloadCenter.getInstance().removeDownloader(tempDownloader);
                _this.changeTableState(tempDownloader, "remove");
                _this.changeCompleteTableState(downloadedJson, 'change')
                //有一个下载成功，继续初始化下载中心，下载之后的课程
                if (callback) {
                    callback()
                }
            },
                function () {
                    //赋值下载失败
                    tempDownloader.centerStatus = 4;
                    _this.changeTableState(tempDownloader, "change");
                    if (callback) {
                        callback()
                    }
                },
                function (progressCallbackVal) {
                    tempDownloader.centerStatus = 2;
                    progressCallbackVal = JSON.parse(progressCallbackVal);
                    _this.changeTableState(tempDownloader, "change", {
                        speed: progressCallbackVal.ReturnValue.DownloadSpeed,
                        progressVal: parseInt(progressCallbackVal.ReturnValue.Progress)
                    });
                });
        });
    }

    runGenerator () {
        let _this = this
        let initId = UUIDUtil.uuid();
        let gen = GeneratorFactory.createGenerator(_this.needLoadingList);
        let executor = new GeneratorExecutor();
        this.generator = executor
        _this.initCenterMap.set(initId, executor);
        executor.run(gen, function () {
            if (_this.initCenterMap.has(initId)) {
                _this.initCenterMap.delete(initId);
            }
        });
    }

    initGeneratorListOneLesson (downloadItem, isUnshift = false) {
        // downloadItem.param.DownloadParams.forEach((item , index)=>{
        //     if (item.FileType == 'BosVideo') {
        //         downloadItem.param.DownloadParams.splice(index,1)
        //     }
        // })
        // console.log('正在下载', downloadItem)

        // return
        let _this = this
        let param = downloadItem.param
        let sqlLib = SqlLib.getInstance(window.$DBDIR);
        let user = SqlLibUser.queryCurrentUser(sqlLib);
        let initSetDownloader = function () {
            downloadItem.centerStatus = 5
            _this.changeTableState(downloadItem, "change")
            return new Promise((resolve, reject) => {
                setTimeout(function () {
                    let tempParam = JSON.stringify(param);
                    let setDownloader = new SetDownloaderLib(param, function () {
                        setDownloader.centerStatus = 0; //初始化成功
                        _this.changeTableState(setDownloader, "change")
                        setDownloader.actionStatus = param.ActionStatus
                        _this.replaceDownloader(setDownloader);
                        param = setDownloader
                        // if (callback) { //如果传了callback ，默认只初始化，不去下载
                        // } else {
                        //     DownloadCenter.getInstance().initDownloadCenter();
                        // }
                        console.log("1.初始化成功！ id::>" + setDownloader.downloaderId);
                        try {
                            let downloader = new Downloader();
                            downloader.id = param.SetDownloadId;
                            downloader.downloadParam = tempParam;
                            downloader.userId = user.id;
                            SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);
                        } catch (e) {
                            console.log(e);
                        }
                        _this.checkDownloadAndNext(downloadItem, setDownloader, resolve, 'success')
                    }, function (error) {
                        if (error !== 'timeout') {
                            setDownloader.centerStatus = 1; //初始化失败
                        } else {
                            setDownloader.centerStatus = 4; //下载失败
                        }
                        setDownloader.actionStatus = param.ActionStatus
                        _this.replaceDownloader(setDownloader);
                        _this.changeTableState(setDownloader, "change")
                        try {
                            let downloader = new Downloader();
                            downloader.id = param.SetDownloadId;
                            downloader.downloaderStatus = "1";
                            downloader.userId = user.id;
                            SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);
                        } catch (e) {
                            console.log(e);
                        }
                        console.log("1.初始化失败！ id::>" + setDownloader.downloaderId);
                        _this.startNextLoadTask(setDownloader.downloaderId)
                        reject("error");
                    });
                }, 1000);
            });
        }
        if (this.loadingLessonList.length < this.downloadingSize) {
            this.loadingLessonList.push({ id: param.SetDownloadId, fn: initSetDownloader })
            this.startOneLoadTask(initSetDownloader)
        } else {
            let waitItem = { id: param.SetDownloadId, fn: initSetDownloader }
            isUnshift ? this.waitDownloadList.unshift(waitItem) : this.waitDownloadList.push(waitItem)
        }
    }

    /**
     * 
     * @param {*} downloadItem 
     * @param {Boolean} isUnshift //用在恢复下载时顶部插入标志
     */
    initGeneratorListAllBook (downloadItem, isUnshift = false) {
        let _this = this
        let param = downloadItem.param
        let currentDownloader = downloadItem.param
        let sqlLib = SqlLib.getInstance(window.$DBDIR);
        let user = SqlLibUser.queryCurrentUser(sqlLib);
        let initSetDownloader = function () {
            return new Promise(((resolve, reject) => {
                downloadItem.centerStatus = 5
                _this.changeTableState(downloadItem, "change")
                setTimeout(function () {
                    DownloadCenter.getInstance().getResAndCoueseware(user.id, param.SetDownloadId, function (lessonItems, itemBsr, isResourceEmpty) {
                        if (!isResourceEmpty) {
                            DownloadCenter.getInstance().request.getResourceInfoByResIds({
                                metaParamDTOS: itemBsr
                            }).then(response => {
                                let bsrResources = response.returnValue.resources;
                                let currentParams = []
                                lessonItems.forEach((item, index) => {
                                    if (bsrResources[item.id]) {
                                        let bsr = bsrResources[item.id];
                                        bsr.brief = item.brief ? item.brief : "";
                                        bsr.intro = item.intro ? item.intro : "";
                                        bsr.scenarios = item.scenarios ? item.scenarios : "";
                                        bsr.meta_info.name = item.name;
                                        item.downloadInfo.Bsr = JSON.stringify(bsr);
                                    }
                                    if (item.downloadInfo.FileType === "courseware" || item.downloadInfo.FileType === "PaperFile") {
                                        item.downloadInfo.Bsr = JSON.stringify(item);
                                    }
                                    currentParams.push(item.downloadInfo);
                                });
                                //备份一份下载参数，方便入库
                                let dbDownloadParams = JSON.stringify({
                                    SetDownloadId: param.SetDownloadId,
                                    DownloaderInfo: param.DownloaderInfo,
                                    DownloadParams: currentParams
                                });
                                let setDownloader = new SetDownloaderLib({
                                    SetDownloadId: param.SetDownloadId,
                                    DownloaderInfo: param.DownloaderInfo,
                                    DownloadParams: currentParams
                                }, function () {
                                    setDownloader.centerStatus = 0; //初始化成功
                                    setDownloader.actionStatus = param.ActionStatus
                                    _this.replaceDownloader(setDownloader);
                                    _this.changeTableState(setDownloader, "change")
                                    try {
                                        let downloader = new Downloader();
                                        downloader.id = param.SetDownloadId;
                                        downloader.downloadParam = dbDownloadParams;
                                        downloader.userId = user.id;
                                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);
                                    } catch (e) {
                                        console.log(e);
                                    }
                                    param = setDownloader
                                    console.log("1.全书课时初始化成功！ id::>" + setDownloader.downloaderId)
                                    _this.checkDownloadAndNext(downloadItem, setDownloader, resolve, 'success')

                                }, function () {
                                    setDownloader.centerStatus = 1; //初始化失败
                                    _this.changeTableState(setDownloader, "change")
                                    try {
                                        let downloader = new Downloader();
                                        downloader.id = param.SetDownloadId;
                                        downloader.downloaderStatus = "1";
                                        downloader.downloadParam = JSON.stringify({
                                            SetDownloadId: param.SetDownloadId,
                                            DownloaderInfo: param.DownloaderInfo,
                                            DownloadParams: currentParams
                                        });
                                        downloader.userId = user.id;
                                        SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(downloader);
                                    } catch (e) {
                                        console.log(e);
                                    }
                                    console.log("1.全书课时初始化失败！ id::>" + setDownloader.downloaderId);
                                    _this.startNextLoadTask(setDownloader.downloaderId)
                                    reject("error");
                                });
                            }).catch(error => {
                                console.log(error)
                                currentDownloader.centerStatus = 1
                                _this.changeTableState(currentDownloader, "change");
                                _this.startNextLoadTask(param.SetDownloadId)
                                reject("error");
                            })
                        } else {
                            //没有需要下载的资源，直接移除
                            DownloadCenter.getInstance().removeDownloader(currentDownloader);
                            _this.changeTableState(currentDownloader, "remove");
                            console.log("发送changeDownloadStatus 事件")
                            let changeEvent = new CustomEvent('changeDownloadStatus', {
                                detail: {
                                    lessonId: currentDownloader.downloaderId,
                                    actionStatus: currentDownloader.actionStatus
                                }
                            });
                            window.dispatchEvent(changeEvent);
                            _this.startNextLoadTask(param.SetDownloadId)
                            resolve("success");
                        }
                    }, function () {
                        currentDownloader.centerStatus = 1;
                        _this.changeTableState(currentDownloader, "change");
                        _this.startNextLoadTask(param.SetDownloadId)
                        reject("error");
                    });
                }, 1000);
            }));
        }
        if (this.loadingLessonList.length < this.downloadingSize) {
            this.loadingLessonList.push({ id: param.SetDownloadId, fn: initSetDownloader })
            this.startOneLoadTask(initSetDownloader)
        } else {
            let waitItem = { id: param.SetDownloadId, fn: initSetDownloader }
            isUnshift ? this.waitDownloadList.unshift(waitItem) : this.waitDownloadList.push(waitItem)
        }

    }

    //针对已经初始化的恢复下载
    initializedLesson (setDownloader) {
        let _this = this
        setDownloader.centerStatus = 6
        this.changeTableState(setDownloader, "change")
        let initSetDownloader = function () {
            return new Promise((resolve, reject) => {
                DownloadCenter.getInstance().startDownloadIsInit([setDownloader], function () {
                    _this.startNextLoadTask(setDownloader.downloaderId)
                    resolve('success')
                })
            })
        }

        if (this.loadingLessonList.length < this.downloadingSize) {
            this.loadingLessonList.push({ id: setDownloader.downloaderId, fn: initSetDownloader })
            this.startOneLoadTask(initSetDownloader)
        } else {
            this.waitDownloadList.unshift({ id: setDownloader.downloaderId, fn: initSetDownloader })
        }
    }

    //针对部分成功进行重新下载
    initFailedRecordLoad (downloadParams) {
        downloadParams.forEach(param => {
            //直接进行重新下载
            if (this.setDownloaders.length === 0) {
                this.changeCompleteTableState(param.SetDownloadId, 'remove')
                this.syncPushDownloadCenter(downloadParams)
                return
            }
            let targetIndex = -1
            this.setDownloaders.forEach((item, index) => {
                if (param.SetDownloadId === item.downloaderId) {
                    targetIndex = index
                    item.centerStatus = 6
                    this.changeTableState(item, 'change')
                    this.changeCompleteTableState(param.SetDownloadId, 'remove')
                    if (item.downloadParames) {
                        this.initGeneratorListOneLesson(item)
                    } else {
                        this.initGeneratorListAllBook(item)
                    }
                }
            })
            if (targetIndex === -1) {
                this.changeCompleteTableState(param.SetDownloadId, 'remove')
                this.syncPushDownloadCenter(downloadParams)
            }
        })
    }

    //判断是否在初始化未完成时进行了暂停
    checkDownloadAndNext (downloadItem, setDownloader, callBack, callBackMessage) {
        if (downloadItem.centerStatus === 3) {
            setDownloader.centerStatus = 3
            this.changeTableState(setDownloader, 'change')
            //全部暂停则不进行下一步
            if (!this.pauseAll) {
                this.startNextLoadTask(downloadItem.downloaderId)
            }
        } else {
            ThumbDownloader.asyncDownloadThumbs(this.request, setDownloader.downloadParames)
            DownloadCenter.getInstance().startDownloadIsInit([setDownloader], () => {
                this.startNextLoadTask(downloadItem.downloaderId)
                callBack(callBackMessage)
            })
            ThumbDownloader.asyncDownloadSubtitles(this.request, setDownloader.downloadParames)
        }
    }

    startOneLoadTask (fn) {
        if (this.loadingLessonList.length > this.downloadingSize) {
            return
        } else {
            fn()
        }
    }
    startNextLoadTask (downloaderId) {
        let targetIndex = -1
        this.loadingLessonList.forEach((item, index) => {
            if (item.id === downloaderId) {
                targetIndex = index
            }
        })
        targetIndex !== -1 && this.loadingLessonList.splice(targetIndex, 1)
        if (this.waitDownloadList.length > 0 && this.loadingLessonList.length < this.downloadingSize) {
            let willLoading = this.waitDownloadList.shift()
            this.loadingLessonList.push(willLoading)
            this.startOneLoadTask(willLoading.fn)
        }
    }

    /**
    * 暂停下载中心中的某几个下载任务, 只能暂停正在下载的任务
    * @param indexes
    * @param isNext 是否触发后续的下载，默认true , 如果是全部暂停，则不触发后续下载
    * @param pauseAll 是否全部暂停
    */
    pauseDownloadCenter (downloadIds, isNext = true, pauseAll = false) {
        if (downloadIds) {
            this.pauseAll = pauseAll
            if (this.pauseAll) {
                //如果是全部暂停
                this.loadingLessonList = []
                this.waitDownloadList = []
                this.setDownloaders.forEach(downloader => {
                    if (downloader.centerStatus === 2) {
                        downloader.cancelDownload()
                    }
                    if (downloader.centerStatus !== 3) {
                        downloader.centerStatus = 3
                        this.changeTableState(downloader, "change");
                    }
                })

                this.pauseAll = false
                return
            }
            //批量暂停
            let downloaders = [];
            //如果在下载
            downloadIds.forEach(id => {
                this.setDownloaders.some(downloader => {
                    if (downloader.downloaderId === id) {
                        if (downloader.centerStatus === 2) { //如果正在下载就暂停下载
                            downloader.cancelDownload();
                            if (isNext) {
                                this.startNextLoadTask(id)
                            } else {
                                let targetIndex = -1
                                this.loadingLessonList.forEach((lesson, index) => {
                                    if (lesson.id === id) {
                                        targetIndex = index
                                    }
                                })
                                targetIndex !== -1 && this.loadingLessonList.splice(targetIndex, 1)
                            }
                        } else {

                            let waitIndex = -1
                            this.waitDownloadList.some((item, index) => {
                                if (item.id === id) {
                                    waitIndex = index
                                    return true
                                }
                            })
                            waitIndex !== -1 ? this.waitDownloadList.splice(waitIndex, 1) : this.startNextLoadTask(id)
                        }
                        downloader.centerStatus = 3; //重新赋值为暂停状态
                        downloaders.push(downloader)
                        return true
                    }
                })
            });
            //改变下载状态
            downloaders.forEach(downloader => {
                this.changeTableState(downloader, "change");
            })
        }

    }


    //恢复下载
    resumeDownloader (downloadIds, isUnshift) {
        downloadIds.forEach(id => {
            this.setDownloaders.some(item => {
                if (item.downloaderId === id) {
                    if ([1, 3, 4].includes(item.centerStatus)) {
                        if (item.startDownload) {
                            this.initializedLesson(item)
                        } else {
                            item.centerStatus = 6
                            this.changeTableState(item, 'change')
                            if (item.downloadParames) {
                                this.initGeneratorListOneLesson(item, isUnshift)
                            } else {
                                this.initGeneratorListAllBook(item, isUnshift)
                            }
                        }
                    }
                    return true
                }
            })
        })
    }

    //取消下载
    cancelDownLoad (downloadIds) {
        if (downloadIds.length === this.setDownloaders.length) {
            this.waitDownloadList = []
            this.loadingLessonList.forEach(item => {
                this.pauseDownloadCenter([item.id], false)
            })
            this.setDownloaders = []
            this.changeTableState('all', 'remove')
            return
        }
        downloadIds.forEach(item => {
            let targetIndex = -1
            let loader = null
            //是否在队列中
            this.setDownloaders.some((setDownloader, index) => {
                if (item === setDownloader.downloaderId) {
                    if (setDownloader.centerStatus === 2) {
                        // 正在下载先取消下载
                        setDownloader.cancelDownload()
                        setDownloader.centerStatus = 3
                        let loadingIndex = -1
                        this.loadingLessonList.some((loadingItem, index) => {
                            if (loadingItem.id === item) {
                                loadingIndex = index
                            }
                            return true
                        })
                        loadingIndex !== -1 && this.loadingLessonList.splice(loadingIndex, 1)
                    } else {
                        //不在下载则直接删除队列
                        let waitIndex = -1
                        this.waitDownloadList.some((waitItem, innerIndex) => {
                            if (waitItem.id === item) {
                                waitIndex = innerIndex
                            }
                            return true
                        })
                        waitIndex !== -1 && this.waitDownloadList.splice(waitIndex, 1)
                    }
                    this.changeTableState(setDownloader, 'remove')
                    targetIndex = index
                    loader = setDownloader
                    return true
                }
            })
            if (targetIndex !== -1) {
                this.setDownloaders.splice(targetIndex, 1)
            }
        })
        this.startNextLoadTask(downloadIds[downloadIds.length - 1])
    }


    /**
     * 从服务端获取资源数据，用于全书下载，刚开始没有数据初始化
     * @param userId
     * @param lessonId
     * @param callback
     */
    getResAndCoueseware (userId, lessonId, callback, errorCallback) {
        let _this = this;
        _this.request.getResAndCouesewareByLessonId({
            lessonId: lessonId
        }).then(response => {
            let result = [];
            let resultBsr = [];
            let resAndCouse = response.returnValue;
            let isResourceEmpty = false;
            if (!resAndCouse.resCoursewaresVOList && !resAndCouse.resourceVOList && !resAndCouse.tResPaperFileVOList) {
                console.log('没有资源---------------------',resAndCouse);
                errorCallback();
                return
            }
            if (resAndCouse.resCoursewaresVOList && resAndCouse.resCoursewaresVOList.length && resAndCouse.resCoursewaresVOList.length > 0) {
                resAndCouse.resCoursewaresVOList.forEach((course, index) => {
                    let courseObj = {
                        id: course.id,
                        name: course.title,
                        resType: "PPT",
                        thumb: course.thumb,
                        downloadInfo: {
                            FileName: course.id + ".pptx",
                            FileType: "courseware",
                            TaskId: course.id,
                            Url: course.url
                        }
                    };
                    if (index === 0) {
                        courseObj.isDefault = "1";
                    } else {
                        courseObj.isDefault = "0";
                    }
                    result.push(courseObj);
                    resultBsr.push({
                        metaId: course.id,
                        metaType: "courseware"
                    });
                });
            }

            if (resAndCouse.resourceVOList && resAndCouse.resourceVOList.length && resAndCouse.resourceVOList.length > 0) {
                let quizes = [];
                resAndCouse.resourceVOList.forEach(resource => {
                    let info = {
                        id: resource.resMetaInfoVO.meta_id,
                        name: resource.name,
                        // resType: '课时资源 | ' + DownloadCenter.getInstance().resTypeToName(resource.resMetaInfoVO.res_type),
                        resType: DownloadCenter.getInstance().resTypeToName(resource.resMetaInfoVO.res_type),
                        thumb: resource.resMetaInfoVO.thumb,
                        brief: resource.brief ? resource.brief : "",
                        intro: resource.intro ? resource.intro : "",
                        scenarios: resource.scenarios ? resource.scenarios : "",
                        downloadInfo: {
                            TaskId: resource.resMetaInfoVO.meta_id,
                            FileType: DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type),
                            FileName: DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type) === "PolyvVideo" ? resource.resMetaInfoVO.meta_id : resource.resMetaInfoVO.meta_id + ".zip",
                            Url: resource.resMetaInfoVO.zip_url ? DownloadCenter.getInstance().constVar.global.cdnResourcePrefix + resource.resMetaInfoVO.zip_url : ""
                        }
                    }
                    resultBsr.push({
                        metaId: resource.resMetaInfoVO.meta_id,
                        metaType: DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type)
                    })
                    if (DownloadCenter.getInstance().resTypeToEnName(resource.resMetaInfoVO.res_type) == "Quiz") {
                        quizes.push(info);
                    } else {
                        result.push(info);
                    }
                });
                result = result.concat(quizes);
            }
            if (resAndCouse.tResPaperFileVOList && resAndCouse.tResPaperFileVOList.length > 0) {
                resAndCouse.tResPaperFileVOList.forEach(resource => {
                    let info = {
                        id: resource.id,
                        name: resource.name,
                        resType: "文档资源",
                        thumb: resource.thumb,
                        brief: resource.brief ? resource.brief : "",
                        intro: resource.intro ? resource.intro : "",
                        scenarios: resource.scenarios ? resource.scenarios : "",
                        downloadInfo: {
                            TaskId: resource.id,
                            FileType: 'PaperFile',
                            FileName: resource.id + ".pdf",
                            Url: resource.url
                        }
                    };
                    resultBsr.push({
                        metaId: resource.id,
                        metaType: 'PaperFile'
                    });
                    result.push(info);
                });
            }
            if (!resAndCouse.resourceVOList && !resAndCouse.resCoursewaresVOList && !resAndCouse.tResPaperFileVOList) {
                isResourceEmpty = true;
            } else {
                if (resAndCouse.resCoursewaresVOList instanceof Array &&
                    resAndCouse.resCoursewaresVOList.length === 0 &&
                    resAndCouse.tResPaperFileVOList instanceof Array &&
                    resAndCouse.tResPaperFileVOList.length === 0 &&
                    resAndCouse.resourceVOList instanceof Array &&
                    resAndCouse.resourceVOList.length === 0) {
                    isResourceEmpty = true;
                }
            }
            if (callback) {
                callback(result, resultBsr, isResourceEmpty);
            }
        }).catch(error => {
            if (errorCallback) {
                errorCallback();
            }
            console.log(error);
        })
    }

    /**
     * 私有方法，方便替换数组中的setDownloader
     * @param setDownloader
     */
    replaceDownloader (setDownloader) {
        let _this = this;
        let index = -1;
        _this.setDownloaders.forEach((downloader, i) => {
            if (downloader.downloaderId === setDownloader.downloaderId) {
                index = i;
            }
        });
        if (index !== -1) {
            _this.setDownloaders.splice(index, 1, setDownloader);
        }
    }

    changeTableState (setDownloader, method, progress) {
        let lesson = null
        if (setDownloader !== 'all') {
            if (Array.isArray(setDownloader)) {
                lesson = []
                setDownloader.forEach((item) => {
                    let downloadInfo = item.downloaderInfo || item.DownloaderInfo || {}
                    let lessonItem = {
                        name: downloadInfo.lessonName,
                        publisher: downloadInfo.publisherName,
                        book: downloadInfo.bookName,
                        id: item.downloaderId,
                        status: item.centerStatus,
                        progress: progress ? progress : {
                            speed: 0,
                            progressVal: 0
                        },
                        // isChecked: false
                    }
                    lesson.push(lessonItem)
                })
            } else {
                let downloadInfo = setDownloader.downloaderInfo || setDownloader.DownloaderInfo || {}
                lesson = {
                    name: downloadInfo.lessonName,
                    publisher: downloadInfo.publisherName,
                    book: downloadInfo.bookName,
                    id: setDownloader.downloaderId,
                    status: setDownloader.centerStatus,
                    progress: progress ? progress : {
                        speed: 0,
                        progressVal: 0
                    },
                    // isChecked: false
                }
            }
        }

        if (method === 'add') {
            lesson.checked = false
            vm.$store.commit('addLoadingLesson', lesson)
        } else if (method === 'change') {
            vm.$store.commit('changeLoadingStatus', lesson)
        } else if (method === 'remove') {
            vm.$store.commit('removeLoadingBook', setDownloader === 'all' ? 'all' : lesson.id)
        }
    }

    changeCompleteTableState (completeLesson, method = 'add') {
        if (method === 'add') {
            vm.$store.commit('addCompletedBook', completeLesson)
        } else if (method === 'change') {
            vm.$store.commit('changeCompletedBook', completeLesson)
        } else if (method === 'remove') {
            vm.$store.commit('removeCompletedBook', completeLesson)
        }
    }
    /**
     * 根据downloader的变化，改变视图层
     * @param setDownloader
     * @param method  :  add   remove   change
     * @param progress  进度
     */
    changeViewTables (setDownloader, method, progress) {
        let _this = this;
        let downloadInfo = setDownloader.downloaderInfo;
        if (downloadInfo) {
            if (method === "add") {
                _this.downloadingTable.push({
                    name: downloadInfo.lessonName,
                    publisher: downloadInfo.publisherName,
                    book: downloadInfo.bookName,
                    id: setDownloader.downloaderId,
                    status: setDownloader.centerStatus,
                    progress: {
                        speed: 0,
                        progressVal: 0
                    },
                    isChecked: false
                });
            } else {
                let curIndex = -1
                _this.downloadingTable.forEach((table, index) => {
                    if (table.id === setDownloader.downloaderId) {
                        curIndex = index;
                    }
                });

                if (method === "remove") {
                    if (curIndex !== -1) {
                        _this.downloadingTable.splice(curIndex, 1);
                    }
                } else if (method === "change") {
                    let isChecked = _this.downloadingTable[curIndex].checked;
                    _this.downloadingTable.splice(curIndex, 1, {
                        name: downloadInfo.lessonName,
                        publisher: downloadInfo.publisherName,
                        book: downloadInfo.bookName,
                        id: setDownloader.downloaderId,
                        status: setDownloader.centerStatus,
                        progress: progress ? progress : {
                            speed: 0,
                            progressVal: 0
                        },
                        checked: isChecked ? isChecked : false
                    });
                }
            }
        }
    }
    /**
     * 删除某个固定的下载器
     * @param setDownloader
     */
    removeDownloader (setDownloader) {
        let _this = this;
        let removeIndex = -1;
        _this.setDownloaders.forEach((downloader, index) => {
            if (downloader.downloaderId === setDownloader.downloaderId) {
                removeIndex = index;
            }
        });
        if (removeIndex !== -1) {
            _this.setDownloaders.splice(removeIndex, 1);
        }
    }

    /**
     * 保存一个课时的资源,同时删除该课程没有的资源
     * @param setDownloader
     */
    async saveOneLessonRes (setDownloader) {
        console.log('同步成功')
        let downloadParams = setDownloader.downloadParames
        console.log(downloadParams);
        let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
        // const fs = require('fs')
        // const getEtag = require('../../utils/qetag')
        downloadParams.forEach((param, index) => {
            let userResource = new UserResource();
            userResource.id = UUIDUtil.uuid();
            userResource.userId = user.id;
            userResource.lessonId = setDownloader.downloaderId;
            userResource.resourceClassify = param.isLessonRes ? param.isLessonRes : "2";
            userResource.resourceType = param.FileType;
            let bsr = param.Bsr;
            if (bsr) {
                bsr = JSON.parse(bsr);
                if (bsr.isDefault) {
                    userResource.isDefault = bsr.isDefault;
                } else {
                    userResource.isDefault = "0"
                }
            } else {
                userResource.isDefault = "0"
            }
            userResource.resourceId = param.TaskId;
            userResource.resourceDescription = param.Bsr;
            userResource.resourceName = param.FileName;
            userResource.sortIndex = index + 1;
            if (setDownloader.errorDownloadTaskIndexes.length > 0 &&
                setDownloader.errorDownloadTaskIndexes.contains(index)) {
                userResource.downloadStatus = "1";
            } else {
                userResource.downloadStatus = "0";
            }
            // if (param.FileType == 'courseware') {
            //     console.log('param',param);
            //     const filePath = window.$DATADIR + `resc/courseware/${param.TaskId}`+'.ppt'
            //     if (fs.existsSync(filePath)) {
            //         const bur = fs.readFileSync(filePath)
            //         getEtag(bur).then(val => {
            //             bsr.fileMd5 = val
            //             userResource.resourceDescription = JSON.stringify(bsr)
            //             console.log('courseware fileMd5 ------------------',val);
            //             SqlLibBook.updateOrInsertOneResource(SqlLib.getInstance(window.$DBDIR), userResource);
            //         })
            //     }
            // }
            SqlLibBook.updateOrInsertOneResource(SqlLib.getInstance(window.$DBDIR), userResource);
        });
        if (setDownloader.actionStatus && (setDownloader.actionStatus === "1" || setDownloader.actionStatus === "0")) { //如果是更新的话,需要把版本号更新掉
            let sqlLib = SqlLib.getInstance(window.$DBDIR);
            let lessonResource = SqlLibUser.queryLessonResource(sqlLib, user.id, setDownloader.downloaderId);
            if (lessonResource instanceof Array) {
                if (lessonResource.length > 0) {
                    let notExsist = [];
                    lessonResource.forEach(res => {
                        let result = false;
                        downloadParams.forEach(param => {
                            if (param.TaskId === res.resourceId || res.resourceClassify !== '2') { //只要存在，及为true
                                result = true;
                            }
                        })
                        if (!result) {
                            notExsist.push(res);
                        }
                    });
                    notExsist.forEach(notExs => {
                        let tempL = new UserResource();
                        tempL.id = notExs.id;
                        sqlLib.deleteObjectById(tempL);
                    })
                }
            }
            let _this = this;
            let updateVersion = function () {
                return new Promise(resolve => {
                    _this.request.getLessonVersion({
                        lessonId: setDownloader.downloaderId
                    }).then(response => {
                        if (response.code == "0") {
                            let tempL = new Lesson();
                            tempL.id = setDownloader.downloaderId;
                            tempL = SqlLib.getInstance(window.$DBDIR).selectObjectById(tempL);
                            tempL.resVersion = response.returnValue.resVersion;
                            SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(tempL);
                        }
                        console.log("更新课程版本号...")
                        resolve("")
                    }).catch(e => {
                        resolve("")
                    })
                })
            }
            await updateVersion();
        }
    }

    /**
     * 从下载中心移除一组下载任务,不能移除正在下载的任务
     * @param downloadIds 下载任务的id数组
     */
    removeDownloadCenter (downloadIds) {
        let _this = this;
        let downloaders = [];
        let indexes = [];
        downloadIds.forEach(downloadId => {
            _this.setDownloaders.forEach((downloader, index) => {
                if (downloader.downloaderId === downloadId) {
                    downloaders.push(downloader);
                    indexes.push(index);
                }
            });
        });
        //删除downloader
        indexes.forEach(index => {
            _this.setDownloaders.splice(index, 1);
        });
        //删除视图
        downloaders.forEach(one => {
            DownloadCenter.getInstance().changeViewTables(one, "remove");
        });
    }




    /**
     * 暂停全部
     */
    pauseAlldownloader () {
        let downloadIds = [];

        //暂停所有的初始化操作
        this.initCenterMap.forEach((value, key) => {
            value.pause();
        });

        //暂停所有的下载器
        this.setDownloaders.forEach(downloader => {
            downloadIds.push(downloader.downloaderId);
        })
        this.pauseDownloadCenter(downloadIds, false);
        //清空列表
        this.setDownloaders.splice(0, this.setDownloaders.length);
        //不去除已经下载过的列表
        // this.downloaded.splice(0, this.downloaded.length);
        this.downloadingTable.splice(0, this.downloadingTable.length);
    }




    /**
     * 恢复单个未初始化的下载器，
     * @param downloadId
     */
    resumeUnInitDownloader (downloadId) {
        console.log("触发 resumeUnInitDownloader...")
        let _this = this;
        if (downloadId) {
            _this.setDownloaders.forEach(downloader => {
                if (downloader.downloaderId === downloadId) {
                    if (downloader.centerStatus === 1 || downloader.centerStatus === 4 || downloader.centerStatus === 5) {
                        downloader.centerStatus = 5; //重置为未初始化状态
                        DownloadCenter.getInstance().changeViewTables(downloader, "change");
                        setTimeout(function () {
                            let user = SqlLibUser.queryCurrentUser(SqlLib.getInstance(window.$DBDIR));
                            DownloadCenter.getInstance().getResAndCoueseware(user.id, downloader.downloaderId, function (lessonItems, itemBsr, isResourceEmpty) {
                                if (!isResourceEmpty) {
                                    DownloadCenter.getInstance().request.getResourceInfoByResIds({
                                        metaParamDTOS: itemBsr
                                    }).then(response => {
                                        let bsrResources = response.returnValue.resources;
                                        let currentParams = []
                                        lessonItems.forEach((item, index) => {
                                            if (bsrResources[item.id]) {
                                                let bsr = bsrResources[item.id];
                                                bsr.brief = item.brief ? item.brief : "";
                                                bsr.intro = item.intro ? item.intro : "";
                                                bsr.scenarios = item.scenarios ? item.scenarios : "";
                                                bsr.meta_info.name = item.name;
                                                item.downloadInfo.Bsr = JSON.stringify(bsr);
                                            }
                                            if (item.downloadInfo.FileType === "courseware") {
                                                item.downloadInfo.Bsr = JSON.stringify(item);
                                            }
                                            currentParams.push(item.downloadInfo);
                                        });
                                        //备份一份下载参数，方便入库
                                        let dbDownloadParams = JSON.stringify({
                                            SetDownloadId: downloader.SetDownloadId,
                                            DownloaderInfo: downloader.DownloaderInfo,
                                            DownloadParams: currentParams
                                        });
                                        downloader = new SetDownloaderLib({
                                            SetDownloadId: downloader.downloaderId,
                                            DownloaderInfo: downloader.downloaderInfo,
                                            DownloadParams: currentParams
                                        }, function () {
                                            downloader.centerStatus = 0; //初始化成功
                                            downloader.actionStatus = downloader.ActionStatus
                                            _this.replaceDownloader(downloader);
                                            DownloadCenter.getInstance().changeViewTables(downloader, "change");
                                            try {
                                                let tempDownloader = new Downloader();
                                                tempDownloader.id = downloader.downloaderId;
                                                tempDownloader.downloadParam = dbDownloadParams;
                                                SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(tempDownloader);
                                            } catch (e) {
                                                console.log(e);
                                            }
                                            //异步去下载缩略图
                                            ThumbDownloader.asyncDownloadThumbs(_this.request, downloader.downloadParames);
                                            ThumbDownloader.asyncDownloadSubtitles(this.request, setDownloader.downloadParames)
                                            console.log("1.全书课时初始化成功！ id::>" + downloader.downloaderId);
                                            DownloadCenter.getInstance().initDownloadCenter();
                                        }, function () {
                                            setDownloader.centerStatus = 4; //初始化失败
                                            DownloadCenter.getInstance().changeViewTables(downloader, "change");
                                            try {
                                                let tempDownloader = new Downloader();
                                                tempDownloader.id = downloader.downloaderId;
                                                tempDownloader.downloaderStatus = "1";
                                                tempDownloader.downloadParam = JSON.stringify({
                                                    SetDownloadId: downloader.downloaderId,
                                                    DownloaderInfo: downloader.downloaderInfo,
                                                    DownloadParams: currentParams
                                                });
                                                SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(tempDownloader);
                                            } catch (e) {
                                                console.log(e);
                                            }
                                            console.log("1.全书课时初始化失败！ id::>" + setDownloader.downloaderId);
                                        });
                                    }).catch(error => {
                                        downloader.centerStatus = 4;
                                        DownloadCenter.getInstance().changeViewTables(downloader, "change");
                                    })
                                } else {
                                    downloader.centerStatus = 0; //初始化成功
                                    downloader.actionStatus = downloader.ActionStatus
                                    _this.replaceDownloader(downloader);
                                    DownloadCenter.getInstance().changeViewTables(downloader, "change");
                                }
                            }, function () {
                                downloader.centerStatus = 4;
                                DownloadCenter.getInstance().changeViewTables(downloader, "change");
                            });
                        }, 1000);
                    }
                }
            })
        }
    }


    findDownloadingIndex () {
        let currentDownloadIds = []
        this.setDownloaders.forEach((downloader, index) => {
            if (downloader.centerStatus === 2) {
                currentDownloadIds.push(downloader.downloaderId);
            }
        });
        return currentDownloadIds;
    }

    /**
     * 寻找下几个待下载的index
     * @param count 下几个（数量）
     * @return {array}
     */
    findNextDownloadDownloader (count) {
        let nextDownloader = [];
        for (let i = 0;i < this.setDownloaders.length;i++) {
            if (nextDownloader.length >= count) {
                break;
            } else {
                if (this.setDownloaders[i].centerStatus === 0) { //初始化成功
                    nextDownloader.push(this.setDownloaders[i]);
                }
            }
        }
        return nextDownloader;
    }

    /**
     * 初始化视图表格
     */
    initDownloadingTable () {
        let _this = this;
        if (_this.setDownloaders && _this.setDownloaders.length > 0) {
            _this.downloadingTable = [];
            _this.setDownloaders.forEach((downloader, index) => {
                let downloadInfo = downloader.downloaderInfo;
                _this.downloadingTable.push({
                    name: downloadInfo.lessonName,
                    publisher: downloadInfo.publisherName,
                    book: downloadInfo.bookName,
                    id: downloader.downloaderId,
                    status: downloader.centerStatus,
                    progress: 0,
                    isChecked: false
                });
            });
        }
    }

    /**
     * 触发下载列表的事件
     * @param index 索引，数组的第几个元素
     * @param value 需要改变的值
     * @param type 操作类型
     */
    touchDownloaderEvent (index, value, type) {
        console.log("touchDownloaderEvent callback index:: " + index + " value:: " + JSON.stringify(value) + " type::" + type)
        let _this = this;
        let downloaderEvent = new CustomEvent('setDownloader', {
            detail: {
                index: index,
                value: value,
                type: type //1.add = push  2.remove = splice 3.change = splice
            }
        });
        if (window.dispatchEvent) {
            window.dispatchEvent(downloaderEvent);
        } else {
            window.fireEvent(downloaderEvent);
        }
    }

    /**
     * 当前的课程是否正在下载
     * @param lessonId
     * @return {boolean}
     */
    lessonIsDownloading (lessonId) {
        let _this = this;
        let isDownloading = false;
        for (let i = 0;i < _this.setDownloaders.length;i++) {
            if (_this.setDownloaders[i].downloaderId === lessonId) {
                isDownloading = true;
                break;
            }
        }
        return isDownloading;
    }

    /**
     * 是否允许加入下载队列
     * @param param
     */
    isDownloaderAlowed (param) {
        let _this = this;
        let result = true;
        for (let i = 0;i < _this.downloaded.length;i++) {
            if (_this.downloaded[i].lessonId === param.SetDownloadId && param.ActionStatus === "0") { //如果是下载状态，且出现在已经下载过的列表里，不允许加入
                result = false;
                break;
            }
        }
        return result;
    }

    /**
     * 返回当前正在下载和已经完成下载的课程id
     */
    getCurrentDownloadLesson () {
        let downloadIds = [];
        vm.$store.state.completedBook.forEach(down => {
            downloadIds.push(down.lessonId);
        });
        DownloadCenter.getInstance().setDownloaders.forEach(downloader => {
            downloadIds.push(downloader.downloaderId);
        });
        return downloadIds;
    }

    /**
     * 返回当前正在下载的课程
     * @return {Array}
     */
    getCurrentDownloadingLesson () {
        let downloadIds = [];
        DownloadCenter.getInstance().setDownloaders.forEach(downloader => {
            downloadIds.push(downloader.downloaderId);
        });
        return downloadIds;
    }

    /**
     * 接口的资源转为需要的资源类型
     * @param resType
     * @return {*}
     */
    resTypeToName (resType) {
        resType = DownloadCenter.getInstance().constVar.global.resourceSwitch[resType];
        return DownloadCenter.getInstance().constVar.global.resourceType[resType];
    }

    resTypeToEnName (resType) {
        return DownloadCenter.getInstance().constVar.global.resourceSwitch[resType];
    }

    recordUserDownloadInfo (param) {
        if(
            param.resourceType === 'selfPpt'  ||
            param.resourceType === 'selfPdf'  ||
            param.resourceType === 'selfWord' ||
            param.resourceType === 'selfImg'  ||
            param.resourceType === 'selfVideo'||
            param.resourceType === 'selfAudio'){
            console.log('自上传的资源下载不统计');
        }else{
            this.request.createUserDownloadInfoRecord(param).then((response) => {
                console.log("资源埋点=>资源下载完成::" + JSON.stringify(param));
            }).catch(error => {
                console.log("资源埋点=>资源下载失败");
            })
        }
    }
}